<?php

use EasyWeChat\Factory;
use Monolog\Logger;
use Phalcon\Mvc\Controller;
use Symfony\Component\Cache\Simple\RedisCache;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\Video;
use EasyWeChat\Kernel\Messages\Voice;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use EasyWeChat\Kernel\Messages\Article;
use EasyWeChat\Kernel\Messages\Media;
use EasyWeChat\Kernel\Messages\Raw;

class WxBaseController extends Controller
{
	protected static $open;
	protected static $site = 'http://drinkt.org.cn';
	protected $link;
	protected $token;
	protected $app_id;
	protected $user;

	/**
	 * initialize
	 */
	public function initialize()
	{

//		$controllerName = strtolower($this->dispatcher->getControllerName());
//		$actionName = strtolower($this->dispatcher->getActionName());
//		$this->link = $controllerName . '/' . $actionName;
//		$this->token = $this->getToken();
//		$this->app_id = $this->getAppId();
//		if (empty($this->token)) {
//			$this->user = null;
//		} else {
//			$tokenHelp = new TokenHelper();
//			$payload = $tokenHelp->verifier($this->token, $this->config->tokenKey);
//			if ($payload == false) {
//				$message = $tokenHelp->getMessage();
//				$this->exitMessage(false, $message);
//			} else {
//				$this->user = $payload['data'];
//			}
//		}
//		if (!empty($this->admin)) {
//			// 检测访问权限
//			$access = $this->accessControl();
//			if (!$access) {
//				$this->exitMessage(false, '权限不足');
//				exit;
//			}
//		}
		$this->getOpen();
	}

	/**
	 * Token 获取
	 * @return string
	 */
	private function getToken()
	{
		$token = $this->request->getHeader('token');
		$getToken = $this->request->get('token');//可能需要从params中获取
		if (empty($token) && !empty($getToken)) {
			$token = $getToken;
		}
		if (empty($token) && isset($_COOKIE['auth-Token'])) {
			$token = $_COOKIE['auth-Token'];
		}

		return $token;
	}

	public function getAppId()
	{
		/**
		 * 暂时返回
		 */
		$app_id = $this->request->getHeader("appid");

		if (!$app_id) {
			$app_id = $this->request->get("app_id");
			if (!$app_id) {
				return '';
			}
		}
		return $app_id;
	}

	public function getMobie()
	{
		$token = $this->request->getHeader('token');
		if (empty($token)) {
			return false;
		} else {
			$tokenHelp = new TokenHelper();
			$payload = $tokenHelp->verifier($token, $this->config->tokenKey);
			$payload = json_encode($payload, JSON_UNESCAPED_UNICODE);
			$payload = json_decode($payload, true);
			return $payload['data']['username'];
		}
	}

	public static function getApp($app_id,$app_screct)
	{
		$config = [
			'app_id' => $app_id,
			'secret' => $app_screct,
			'response_type' => 'array'
		];

		$app = EasyWeChat\Factory::officialAccount($config);
		return $app;
	}
	/**
	 * 获取开放平台配置
	 */
	private function getOpen()
	{

		$config = [
			'app_id' => 'wxac38b1d46627cf43',
			'secret' => '4409cc4427f9111a3cd4045c8a137ee5',
			'token' => 'dsion3io2ngd09s990482',
			'aes_key' => 'zrwz2HRxXpMVFrs6e5GdevhtBzQmyptuz4gaXSk5678',
            'debug' => true,
			'log' => [
				'default' => 'prod',
				'channels' => [
					'dev' => [
						'driver' => 'single',
						'path' => '/web/haidao/logs/easywechat.log',
						'level' => 'debug',
					],
					'prod' => [
						'driver' => 'daily',
						'path' => '/web/haidao/logs/easywechat.log',
						'level' => 'info',
					],
				],
			],
		];
		self::$open = EasyWeChat\Factory::openPlatform($config);


//		$cache = new RedisCache($this->redis);

//		self::$open->rebind('cache', $cache);
	}


	/**
	 * 检查是否登陆
	 */
//    protected function checkHasLogin()
//    {
//        if (empty($this->user)) {
//            $this->exitMessage(false, '用户没有登录，请登陆');
//            exit;
//        }
//    }


	//检查是否已登录，否则返回登录页面
//    public function checkHasLogin() {
//        if(empty($this->user)){
//            if($this->request->isPost()||$this->request->isAjax()){
//                $this->exitMessage(false,"请登录后再操作");
//            }
//            $url = "http://weiwei.zwnjs.com/SsoLogin";
//            header('Location: '. $url);
//            exit;
//        }
//    }

	private function accessControl()
	{
		//暂不做权限控制
		return true;
	}

	/**
	 * 输出JSON信息
	 * @param bool $status
	 * @param string $message
	 * @param null $data
	 * @param null $token
	 */
	public function exitMessage($status = false, $message = '', $data = null, $token = null)
	{
		$info = new stdClass();
		$info->status = $status;
		$info->message = $message;
		$info->data = $data;
		if ($token) {
			$info->token = $token;
		}
		header('Content-type:application/json');
		exit(json_encode($info, JSON_UNESCAPED_UNICODE));
	}

	public function joinWhere( $whereArr ) {
		if( empty($whereArr) ) return '';
		return implode(' and ', $whereArr);
	}

	/**
	 * 获取RefreshToken
	 * @param $app_id
	 * @return bool|string
	 */
	protected function getRefreshToken($app_id)
	{
		//从缓存获取RefreshToken
		$refreshToken = $this->redis->get('ww:refresh:token:' . $app_id);
		if (!$refreshToken) {
			$refreshToken = AuthorizedApp::findFirst("app_id = '{$app_id}'");
			if ($refreshToken) {
				$refreshToken = $refreshToken->refresh_token;
				$this->redis->setEx('ww:refresh:token:' . $app_id,10000, $refreshToken);
			} else {
				return false;
			}
		}
		return $refreshToken;
	}

	/**
	 * 根据OpenId获取用户信息
	 * @param $app_id
	 * @param $open_id
	 * @param $officialAccount
	 * @return bool|string
	 */
	protected function getUserInfo($app_id, $open_id, $officialAccount)
	{
		$key = 'ww:user:info:token:' . $app_id . ':' . $open_id;
		//从缓存获取RefreshToken
		$userInfo = $this->redis->get($key);
		if (!$userInfo) {
			$userInfo = $officialAccount->user->get($open_id);
			$userInfoJson = json_encode($userInfo, JSON_UNESCAPED_UNICODE);
			$this->redis->setEx($key, 86400, $userInfoJson);
			return $userInfo;
		} else {
			return json_decode($userInfo, true);
		}
	}

	/**
	 * 获取媒体ID
	 * @param $app
	 * @param $path
	 * @param $type
	 * @return bool|int
	 */
	protected function getMediaId($app, $path, $type)
	{
		$key = 'ww:' . md5($path);
		$mediaId = $this->redis->get($key);
		$realPath = FileHelper::getRealPath($path);
		if (!$mediaId) {
			switch ($type) {
				case 'image':
					$mediaId = UploadToWeixin::images($app, $realPath, $this->redis);
					break;
				case 'voice':
					$mediaId = UploadToWeixin::voice($app, $realPath, $this->redis);
					break;
				case 'video':
					$mediaId = UploadToWeixin::video($app, $realPath, $this->redis);
					break;
				default:
					return false;
			}
			if (!$mediaId) {
				return false;
			}
		}
		return $mediaId;
	}

	/**
	 * 返回指定分类消息
	 * @param $appId
	 * @param $divisive
	 * @param $taskId
	 * @return Message|Message[]|\Phalcon\Mvc\Model\ResultSetInterface
	 */
	protected function getMsgs($appId, $divisive, $taskId = 0)
	{
		if (!empty($taskId)) {
			$conditions = "app_id = '{$appId}' and divisive = '{$divisive}' and task_id = '{$taskId}' and enabled = 1";
		} else {
			$conditions = "app_id = '{$appId}' and divisive = '{$divisive}' and enabled = 1";
		}
		$msgs = Message::find([
			'conditions' => $conditions,
			'order' => 'sort'
		]);
		return $msgs;
	}

	/**
	 * 发送客服消息
	 * @param $openId
	 * @param $appId
	 * @param $msg
	 * @return bool
	 */
	protected function sendMsg($openId, $appId, $msg)
	{

		$refreshToken = $this->getRefreshToken($appId);
		if (!$refreshToken) {
			return false;
		}
		$officialAccount = self::$open->officialAccount($appId, $refreshToken);

		$type = $msg->type;
		$userName = '';
		if ($type === 'text' && strpos($msg->desc, '${name}') !== false) {
			$userInfo = $this->getUserInfo($appId, $openId, $officialAccount);
			if ($userInfo && isset($userInfo['nickname'])) {
				$userName = $userInfo['nickname'];
			}
		}
		if (in_array($type, ['image', 'voice', 'video'])) {
			$mediaId = $this->getMediaId($officialAccount, $msg->img_url, $type);
			if (!$mediaId) {
				return false;
			}
			$msg->img_url = $mediaId;
		}
		//图文图片地址
		if ($type === 'news'){
			$msg->img_url = BASE_URL.$msg->img_url;
		}
		$message = MsgHelper::createMsg($type, $msg, $userName);
		if ($type === 'news') {
			$message = new News([$message]);
		}
		$result = $officialAccount->customer_service->message($message)->to($openId)->send();

		return $result['errcode'] === 0;
	}
	protected function sendKeyWordMsg($openId, $appId, $msg,$img_id)
	{
		try{
            MyLog::setLog(['open_id'=>$openId,'appId'=>$appId,'msg'=>$msg,'img_id'=>$img_id], 'ccc', Logger::INFO, '', '', PUBLIC_PATH . "/log/" . __CLASS__ . "/" . date("Ymd") . "/" . __FUNCTION__ . "_ccc.log");
			$refreshToken = $this->getRefreshToken($appId);
			$appinfo = AuthorizedAppInfo::findFirst("app_id='{$appId}'");
			$wxh_info = $this->redis->get($openId.":keyword:".$img_id);
			if(!$wxh_info){
				$wxh_info = $this->db->fetchAll("select img_path,wxh_id,media_id from delay_media where app_id='{$appId}' and is_delete=0 and img_id={$img_id}");
				$num = rand(0, count($wxh_info) - 1);
				ImgQrDetails::saveLog($appId,$openId,$wxh_info[$num]['img_path'],"key_word");
                $this->redis->set($openId.":keyword:".$img_id,json_encode($wxh_info[$num]));
				$wxh_info = $this->redis->get($openId.":keyword:".$img_id);
			}
            MyLog::setLog([$wxh_info], 'ccc', Logger::INFO, '', '', PUBLIC_PATH . "/log/" . __CLASS__ . "/" . date("Ymd") . "/" . __FUNCTION__ . "_ccc.log");

			if (!$refreshToken) {
                MyLog::setLog(['msg'=>'token失效'], 'ccc', Logger::INFO, '', '', PUBLIC_PATH . "/log/" . __CLASS__ . "/" . date("Ymd") . "/" . __FUNCTION__ . "_ccc.log");
				return false;
			}

			$officialAccount = self::$open->officialAccount($appId, $refreshToken);

			$type = $msg->type;
			$wxh_info=json_decode($wxh_info,1);
			switch ($type){
				case "text":
					$userInfo = $this->getUserInfo($appId, $openId, $officialAccount);
					$userName = $userInfo['nickname'];
					$message = str_replace("{{name}}",$userName,$msg->desc);
					$message = str_replace("{{wxh_id}}",$wxh_info['wxh_id'],$message);
					$message = new Text($message);
					$send_msg=["content"=>date("Y-m-d H:i:s")."\r\n公众号：".$appinfo->nick_name."\r\n关键字回复发送失败\r\n消息：文字消息\r\n接收人：".$userName."\r\n请联系技术排查问题"];
					break;
				case "image":
					$userInfo = $this->getUserInfo($appId, $openId, $officialAccount);
					$userName = $userInfo['nickname'];
					$message = new Image($wxh_info['media_id']);
					$send_msg=["content"=>date("Y-m-d H:i:s")."\r\n公众号：".$appinfo->nick_name."\r\n关键字回复发送失败\r\n消息：文字消息\r\n接收人：".$userName."\r\n请联系技术排查问题"];
                    $this->redis->del($openId.":keyword:".$img_id);
					break;
			}
//			$officialAccount->customer_service->message(new Text(json_encode($msg,JSON_UNESCAPED_UNICODE)))->to($openId)->send();
			$result = $officialAccount->customer_service->message($message)->to($openId)->send();
			$keyword_res=new KeywordMessageResult();
			$keyword_res->app_id=$appId;
			$keyword_res->kid=$msg->task_id;
			$keyword_res->msg_id=$msg->id;
			$keyword_res->errcode=$result['errcode'];
			$keyword_res->errmsg=$result['errmsg'];
			$keyword_res->create_at=date("Y-m-d H:i:s");
			$keyword_res->save();
			$all = [
				'010666593026240133',      //杨才俊     13757619801
				'03133136132496',          //卢仙红     15258838059
				"18454224221222463",       //陈璇       18143464872
				"063644012426073849",      //李倩娴     18758228105
				'015455220421420294',        //通知周依媛   15755363818
				'04615943681257639',       //通知自己   15755363818
			];
			if($result['errcode']!=0){
				$this->send($send_msg,$all);
			}
		}catch (Exception $e){
			MyLog::setLog([$e->getMessage(), $e->getFile(), $e->getLine()], 'exception', Logger::INFO, '', '', PUBLIC_PATH . "/log/" . __CLASS__ . "/" . date("Ymd") . "/" . __FUNCTION__ . "_exception.log");
		}
	}


	/**
	 * 数据签名认证
	 *
	 * @param array $data
	 *        	被认证的数据
	 * @return string 签名
	 */
	function data_auth_sign($data) {
		// 数据类型检测
		if (! is_array ( $data )) {
			$data = ( array ) $data;
		}
		ksort ( $data ); // 排序
		$code = http_build_query ( $data ); // url编码并生成query字符串
		$sign = sha1 ( $code ); // 生成签名
		return $sign;
	}

	private function send($msg, $userid_list = "")
	{
		try {
			if ($userid_list == "") {
				//测试通知自己
				$userid_list = '04615943681257639';
			}
			$dingTalk = new DingTalk();
			$dingTalk->sendCorpMsgForMsgTask(json_encode($msg, JSON_UNESCAPED_UNICODE), implode(',',$userid_list), false, false, 'text');
		} catch (Exception $e) {
			MyLog::setLog([$e->getMessage(), $e->getFile(), $e->getLine()], 'send_error', Logger::INFO, '', '', PUBLIC_PATH . "/log/" . __CLASS__ . "/" . date("Ymd") . "/" . __FUNCTION__ . "_exception.log");
		}
	}

}
